/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entity.Event;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import entity.Invitation;
import entity.User;
import java.util.ArrayList;
import java.util.Collection;

@Stateless
public class InvitationManager {

    @PersistenceContext
    private EntityManager em;

    public List<Invitation> getAllInvitation()
       {
             return em.createNamedQuery(Invitation.INVITATIONS_FIND_ALL, Invitation.class)
                             .getResultList();  
       }

    public List<Invitation> getAllInvitationUser(User userBean)
       {
            List<Invitation> inviti = new ArrayList<Invitation>();

            inviti = em.createNamedQuery(Invitation.INVITATIONS_BY_USER, Invitation.class)
                         .setParameter("user", userBean).getResultList();

            return inviti;
                 
           
       }

    public void cancelInvitations(Collection<Invitation> invitations){
        for(Invitation i:invitations){
            Invitation ac = em.getReference(Invitation.class, i.getInvitationPK());
            if (ac != null)
            {
                em.remove(ac);
            }
        }
    }
    
    public boolean UpdateInvitation( Invitation invitation ){
        Invitation mergeInvitation = em.merge( invitation );
        mergeInvitation.setAnswer(invitation.getAnswer());
        return true;
    }
    
    public void invitaAmici(List<User> usersSelected, Event oldEvent,Event newEvent){
        int presente;
        // se il vecchio evento aveva invitati controllo se ci sono nuovi invitati
        
        if(oldEvent.getInvitationCollection()!= null && oldEvent.getInvitationCollection().size()>0){
            for(User u:usersSelected){
                presente=0;
                for(Invitation i:oldEvent.getInvitationCollection()){
                    if(u.equals(i.getUser())){
                        presente=1;
                        break;
                    }
                }
                if(presente == 0){
                    Invitation newI = new Invitation(newEvent,u,0);
                    em.persist(newI);
                }
            }
           
        }
        else{
            newInvitations(usersSelected,newEvent);
        }
    }
    public void newInvitations(List<User> usersSelected,Event event){
        for(User u: usersSelected){
            System.out.println("utente dell'invito"+u.getNickname());
            System.out.println("evento dell'invito"+event.getName());
            
            Invitation in = new Invitation(event,u,0);
            em.persist(in);
        }

    }
}

